import { HttpException, Injectable } from '@nestjs/common';
import { TypeOrmCrudService } from '@dataui/crud-typeorm';
import { Weather } from '@/module/weather/entities/weather.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { httpClint } from '@/utils/http.service';
import { formatDate } from '@/utils/time';

@Injectable()
export class WeatherService extends TypeOrmCrudService<Weather> {
  constructor(
    @InjectRepository(Weather) repo: Repository<Weather>,
    private readonly ahttpClient: httpClint,
  ) {
    super(repo);
  }

  async createOneById(req: any, dto: any): Promise<Weather> {
    const weather = await this.ahttpClient.originApi({
      url:
        'https://api.seniverse.com/v3/weather/now.json?key=SA8x5W-yCX9oaFJix&location=' +
        dto.machineAddress +
        '&language=zh-Hans&unit=c',
      method: 'get',
    });
    // const arr = [
    //   '吴起',
    //   '安塞',
    //   '铜川',
    //   '杨陵',
    //   '韩城',
    //   '西安',
    //   '兴平',
    //   '富平',
    //   '山阳',
    //   '镇安',
    //   '神木',
    //   '商南',
    //   '长武',
    //   '安康',
    //   '华阴',
    //   '榆林',
    //   '略阳',
    //   '黄龙',
    //   '眉县',
    //   '宜君',
    //   '扶风',
    //   '陕西彬县',
    //   '延长',
    //   '宁强',
    //   '洛南',
    //   '户县',
    //   '平利',
    //   '蓝田',
    //   '咸阳',
    //   '潼关',
    //   '洋县',
    //   '汉滨',
    //   '宁陕',
    //   '南郑',
    //   '镇巴',
    // ];

    // for (let i = 0; i < arr.length; i++) {
    //   console.log(arr[i]);
    //
    //   const weather = await this.ahttpClient.originApi({
    //     url:
    //       'https://api.seniverse.com/v3/weather/now.json?key=SNKF9EHegDNjy5og_&location=' +
    //       arr[i] +
    //       '&language=zh-Hans&unit=c',
    //     method: 'get',
    //   });
    //   console.log(weather.results[0].location.path);
    //   console.log(weather.results[0].now.text);
    // }
    const dateStr = formatDate(new Date());
    console.log(weather);
    console.log(req, dto);
    // const one = await this.repo.findOne({
    //   where: {
    //      weatherDate: new Date(),
    //     testingMachine: {
    //       id: dto.testingMachineId,
    //     },
    //   },
    // });
    const one = await this.repo
      .createQueryBuilder('weather')
      .where('DATE(weather.weatherDate) = DATE(:date)', { date: new Date() })
      .andWhere('weather.testingMachineId = :testingMachineId', {
        testingMachineId: dto.testingMachineId,
      })
      .getOne();

    if (one) {
      // throw new HttpException('该日期已存在', 400);
      console.log('you l e');
      return null;
    }
    const weatherData = await this.repo.save({
      weatherDate: new Date(),
      testingMachine: {
        id: dto.testingMachineId,
      },
      weatherData: weather.results[0],
    });
    return weatherData;
  }
}
